package cn.com.w.simple.demo.service.impl;

import cn.com.w.simple.demo.entity.UserInfo;
import cn.com.w.simple.demo.service.IUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


/**
 * 用户信息 服务实现类
 */
@Service
@Slf4j
public class UserInfoServiceImpl implements IUserInfoService, UserDetailsService {


    /**
     * 根据用户名获取用户信息
     *
     * @param s 用户名(指的是唯一的登录名或账号)
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 模拟从数据库获取用户
        List<UserInfo> userInfos = UserInfo.getDefaultList();
        Optional<UserInfo> first = userInfos.stream().filter(i -> i.getLoginName().equals(s)).findFirst();
        if (!first.isPresent()) {
            // 若没查询到一定要抛出该异常，这样才能被Spring Security的错误处理器处理
            throw new UsernameNotFoundException("没有找到该用户");
        }
        return first.get();
    }


}
